package com.leps.nq.op.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leps.nq.common.vo.PageVo;
import com.leps.nq.op.entity.OpMonthlyTask;
import com.leps.nq.op.mapper.OpMonthlyTaskMapper;
import com.leps.nq.op.service.IOpMonthlyTaskService;
import com.leps.nq.op.vo.MonthlyTaskQueryModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 * 月度任务表 服务实现类
 * </p>
 *
 * @author hex
 * @since 2022-05-22
 */
@Service
public class OpMonthlyTaskServiceImpl extends ServiceImpl<OpMonthlyTaskMapper, OpMonthlyTask> implements IOpMonthlyTaskService {
    @Autowired
    OpMonthlyTaskMapper monthlyTaskMapper;

    @Override
    public PageVo<OpMonthlyTask> pageByQueryModel(MonthlyTaskQueryModel queryModel) {
        Page<OpMonthlyTask> page = Page.of(queryModel.getPageNum(), queryModel.getPageSize());
        page = this.monthlyTaskMapper.selectByQueryModel(page, queryModel);
        return PageVo.of(page);
    }

    @Override
    public OpMonthlyTask getByYearAndMonth(int year, int month) {
        return this.lambdaQuery()
                .eq(OpMonthlyTask::getTaskYear, year)
                .eq(OpMonthlyTask::getTaskMonth, month).one();
    }

    @Override
    public boolean updateCompletionByIncrement(Double germicideDosage, Double crrosionInhibitorDosage, Integer year, Integer month, Integer teamId) {
            if (germicideDosage == null) germicideDosage = 0D;
            if (crrosionInhibitorDosage == null) crrosionInhibitorDosage = 0D;
            BigDecimal increment = BigDecimal.valueOf(germicideDosage + crrosionInhibitorDosage);
            OpMonthlyTask monthlyTask = this.lambdaQuery()
                    .eq(OpMonthlyTask::getTeamId, teamId)
                    .eq(OpMonthlyTask::getTaskYear, year)
                    .eq(OpMonthlyTask::getTaskMonth, month).one();
            // may be, system has no monthlytask data.
            if (monthlyTask == null) return true;
            BigDecimal completedValue = monthlyTask.getCompletedValue().add(increment);
            BigDecimal completedRate = completedValue.divide(monthlyTask.getTaskGoal());
            monthlyTask.setCompletedValue(completedValue);
            monthlyTask.setCompletionRate(completedRate);
            return 1 == this.monthlyTaskMapper.updateById(monthlyTask);
    }

    @Override
    public boolean updateCompletionByTeamIdAndYearMonth(Integer teamId, Integer year, Integer month) {
        int rows = this.monthlyTaskMapper.updateCompletion(teamId, year, month);
        return rows == 1;
    }

    @Override
    public void updateCompletionAfterImportExcel() {
        System.out.println("========================>" + Thread.currentThread().getName());
        this.monthlyTaskMapper.updateCompletionAfterImportExcel();
    }
}
